#include "ina226.h"
//读2个字节,reg_addr为读的寄存器地址
int16_t INA226_Read2Byte(u8 reg_addr)
{
    u16 reg_data=0;
    u16 temp=0;
    I2C_Start();
    I2C_SendByte(WRITE_ADDR);
		I2C_WaitAck();
    I2C_SendByte(reg_addr);
    I2C_WaitAck();
	  I2C_Stop();
    I2C_Start();
    I2C_SendByte(READ_ADDR);
    I2C_WaitAck();
    reg_data= I2C_ReceiveByte();
    reg_data=(reg_data<<8)&0xFF00;
	  I2C_SendACK(0);
    temp=I2C_ReceiveByte();
	  I2C_SendACK(1);
    I2C_Stop();
    reg_data|=temp;
    return reg_data;
}
//写2个字节，reg_addr为写的寄存器地址,reg_data为写的数据
uint8_t INA226_Write2Byte(u8 reg_addr,u16 reg_data)
{
    u8 data_high=(u8)((reg_data&0xFF00)>>8);
    u8 data_low=(u8)reg_data&0x00FF;
    I2C_Start();
    I2C_SendByte(WRITE_ADDR);
    I2C_WaitAck();
    I2C_SendByte(reg_addr );
    I2C_WaitAck();
    I2C_SendByte(data_high);
    I2C_WaitAck();
    I2C_SendByte(data_low);
    I2C_WaitAck();
    I2C_Stop();
    delay_ms(2);
    return 1;
}

void INA226_IIC_Init(void)
{
I2C_GPIO_Init();
}
void INA226_Init(void)
{
    INA226_IIC_Init();  //初始化接口
    delay_ms(10);

    //写配置寄存器
    INA226_Write2Byte(Config_Reg, 0x4527);//0100_010_100_100_111 //16次平均,1.1ms,1.1ms,连续测量分流电压和总线电压

    //写校准寄存器
    //LSB选择0.256mA,分压电阻选0.005R Cal=0.00512/(0.256mA*0.005R)=4
    INA226_Write2Byte(Calib_Reg, 0x0800);
}
//获取分流电流mA
float INA226_Get_Current(void)
{
//    float Curent;
//    Curent=INA226_Read2Byte(Current_Reg)*0.256; //分流电流LSB选择0.02mA
//    printf("data=%-5d, Curent =%f mA\r\n", INA226_Read2Byte(Current_Reg),Curent);
//    return Curent;
	
	
//	if((INA226_Read2Byte(Current_Reg)*0.25)<0)
//	return INA226_Read2Byte(Current_Reg)*0.25+64;
  return INA226_Read2Byte(Current_Reg)*0.25;
}
//获取功率
float INA226_Get_Power(void)
{
//    float Power;
//    Power=INA226_Read2Byte(Power_Reg)*0.256*25;//功率LSB固定分流电流LSB的25倍
//    printf("data=%-5d, Power=%f mW\r\n", INA226_Read2Byte(Power_Reg),Power);
//    return Power;
    return INA226_Get_Current()*INA226_Get_Voltage()*0.001;
}
//获取电压
float INA226_Get_Voltage(void)
{
//    float Power;
//    Power=INA226_Read2Byte(Power_Reg)*0.256*25;//功率LSB固定分流电流LSB的25倍
//    printf("data=%-5d, Power=%f mW\r\n", INA226_Read2Byte(Power_Reg),Power);
//    return Power;
    return INA226_Read2Byte(Bus_V_Reg)*1.25;
}



